import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		musicInfo: {
			playStatus: false,
			duration: 0,
			currentTime: 0,
			musicId: 0,
			url: '',
			name: '',
			authors: '',
			picUrl: ''
		},
		bgAudioMannager: {}
	},
	getters: {
		playStatus: state => state.musicInfo.playStatus,
		duration: state => state.musicInfo.duration,
		currentTime: state => state.musicInfo.currentTime,
		musicId: state => state.musicInfo.musicId,
		musicInfo: state => state.musicInfo,
		bgAudioMannager: state => state.bgAudioMannager
	},
	mutations: {
		changeMusicInfo(state, newObj) {
			state.musicInfo = Object.assign(state.musicInfo, newObj)
			uni.setStorageSync('musicInfo',state.musicInfo)
			// console.log(JSON.stringify(state.musicInfo))
		}
	},
	actions: {
		createBg({
			commit,
			state
		}) {
			state.bgAudioMannager = uni.getBackgroundAudioManager();
			state.bgAudioMannager.title = state.musicInfo.name;
			state.bgAudioMannager.singer = state.musicInfo.authors;
			state.bgAudioMannager.src = state.musicInfo.url;
			// commit('changeMusicInfo', {
			// 	url: '',
			// 	name: '',
			// 	authors: '',
			// 	picUrl: '',
			// 	currentTime: 0,
			// 	playStatus: false,
			// 	duration: 0
			// });

			state.bgAudioMannager.onPlay(() => {
				commit('changeMusicInfo', {
					playStatus: true
				});
			});

			state.bgAudioMannager.onTimeUpdate(() => {
				commit('changeMusicInfo', {
					currentTime: state.bgAudioMannager.currentTime
				});
			});

			state.bgAudioMannager.onPause(() => {
				commit('changeMusicInfo', {
					playStatus: false
				});
			});
		},
		play({
			commit,
			dispatch,
			state
		}, args) {
			state.bgAudioMannager.play();
		},
		pause({
			commit,
			state
		}) {
			state.bgAudioMannager.pause()
		},
		seek({
			state
		}, currentTime) {
			state.bgAudioMannager.seek(currentTime)
		}
	}
})
export default store
